import {
  createRouter,
  createWebHashHistory
} from 'vue-router'
import Home from "@/views/Home.vue"
import {
  ElMessage
} from 'element-plus'
const routes = [{
  path: "/",
  name: "root",
  component: Home,
  meta: {
    title: 'Home'
  }
}, {
  path: "/home",
  name: "home",
  component: Home,
  meta: {
    title: 'Home'
  }
},
{
  path: "/login",
  name: "login",
  component: () => import('@/views/Login.vue'),
  meta: {
    title: '登陆'
  }
}, {
  path: "/invoice/info",
  name: "inv-info",
  component: () => import('@/views/InvInfo.vue'),
  meta: {
    requiresAuth: true,
    title: "发票解析"
  }
}, {
  path: "/invoice/full",
  name: "inv-full",
  component: () => import('@/views/InvFull.vue'),
  meta: {
    requiresAuth: true,
    title: "全票面解析"
  }
}, {
  path: "/invoice/info/all",
  name: "inv-info-all",
  component: () => import('@/views/InvHistory.vue'),
  meta: {
    requiresAuth: true,
    title: "历史发票"
  }
}, {
  path: "/invoice/check",
  name: "inv-check",
  component: () => import('@/views/InvCheck.vue'),
  meta: {
    requiresAuth: true,
    title: "发票查验"
  },
}, {
  path: "/alipay",
  name: "alipay",
  component: () => import('@/views/Alipay.vue'),
  meta: {
    requiresAuth: true,
    title: "支付"
  },
}, {
  path: "/userinfo",
  name: "userinfo",
  component: () => import('@/views/UserInfo.vue'),
  meta: {
    requiresAuth: true,
    title: "用户信息"
  },
}, {
  path: '/404', //404
  name: '404',
  component: () => import('@/views/NotFound.vue')
}, {
  path: '/:pathMatch(.*)', // 页面不存在的情况下会跳到404页面
  redirect: '/404',
  name: 'notFound',
  hidden: true
}
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? `${to.meta.title}|永春小站` : `${to.name}|永春小站`
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!localStorage.getItem("token")) {
      ElMessage.warning('未登录，请先登陆!')
      next({
        name: 'login',
        query: {
          redirect: to.fullPath
        }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router